/**
 * $Id: GraphMlPort.java,v 1.1 2011-09-19 15:10:46 gaudenz Exp $
 * Copyright (c) 2010 David Benson, Gaudenz Alder
 */
package com.kg.rails.component.editor.io.graphml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.util.HashMap;
import java.util.List;

/**
 * Represents a Port element in the GML Structure.
 */
public class GraphMlPort {
    private String name;

    private HashMap<String, GraphMlData> portDataMap = new HashMap<String, GraphMlData>();

    /**
     * Construct a Port with name.
     *
     * @param name Port Name
     */
    public GraphMlPort(String name) {
        this.name = name;
    }

    /**
     * Construct a Port from a xml port Element.
     *
     * @param portElement Xml port Element.
     */
    public GraphMlPort(Element portElement) {
        this.name = portElement.getAttribute(GraphMlConstants.PORT_NAME);

        //Add data elements
        List<Element> dataList = GraphMlUtils.childsTags(portElement,
                GraphMlConstants.DATA);

        for (Element dataElem : dataList) {
            GraphMlData data = new GraphMlData(dataElem);
            String key = data.getDataKey();
            portDataMap.put(key, data);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public HashMap<String, GraphMlData> getPortDataMap() {
        return portDataMap;
    }

    public void setPortDataMap(HashMap<String, GraphMlData> nodeDataMap) {
        this.portDataMap = nodeDataMap;
    }

    /**
     * Generates a Key Element from this class.
     *
     * @param document Document where the key Element will be inserted.
     * @return Returns the generated Elements.
     */
    public Element generateElement(Document document) {
        Element node = document.createElement(GraphMlConstants.PORT);

        node.setAttribute(GraphMlConstants.PORT_NAME, name);

        for (GraphMlData data : portDataMap.values()) {
            Element dataElement = data.generateNodeElement(document);
            node.appendChild(dataElement);
        }

        return node;
    }
}
